;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Account.Invoice", [])
        .controller("InvoiceCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$timeout", "$filter", "EventBus", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, $timeout, $filter, EventBus) {
            var btnPermissionCode = {
                invoiceExport: window.ActionCode.invoiceExport,
                invoiceSign: window.ActionCode.invoiceSign,
                invoiceEdit: window.ActionCode.invoiceEdit,
                updateSAP: window.ActionCode.invoiceUpdateSAP
            };
            var invoiceNo = "";

            $scope.activeFlag = [true, false];
            $scope.btnPermission = {
                invoiceExport: true,
                invoiceSign: true,
                invoiceEdit: true,
                updateSAP: true
            };
            $scope.invoiceObj = "";
            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.syncTime = {
                startDateStr: null,
                endDateStr: null,
            }
            $scope.tableConfig = {
                scrollWidth: 1600,
                tableCol: [
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 60,
                        isShow: true,
                        isFixed: true
                    },
                    {
                        name: "开票凭证",
                        dataField: "invoiceNo",
                        width: 100,
                        toSort: false,
                        isShow: true,
                        type: "click",
                        clickFn: "viewDetail"
                    },
                    {
                        name: "纸质发票号",
                        dataField: "invoicePaperNo",
                        width: 100,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "票据金额",
                        dataField: "price",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "开票类型",
                        dataField: "invoiceTypeShow",
                        isShow: true,
                        width: 80,
                    },
                    {
                        name: "开票方",
                        dataField: "orgName",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "付款方",
                        dataField: "payerOrgName",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "签收状态",
                        dataField: "signState",
                        width: 100,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "签收人",
                        dataField: "signName",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "签收说明",
                        dataField: "signNote",
                        width: 150,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "签收时间",
                        dataField: "signDateF",
                        width: 130,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "单据创建时间",
                        dataField: "orderDateF",
                        width: 130,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "过账时间",
                        dataField: "postDateF",
                        width: 130,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "创建时间",
                        dataField: "createDateF",
                        width: 130,
                        toSort: false,
                        isShow: true
                    }
                ]
            };
            $scope.dataList = [];
            $scope.toolbarConfig = {};
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/invoice/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/invoice/exportAll")
            };
            $scope.condition = {};

            $scope.changeTab = function (index) {
                angular.forEach($scope.activeFlag, function (activeFlag) {
                    activeFlag = false;
                });
                $scope.activeFlag[index] = true;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        break;
                    default:
                        break;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.toolbarConfig["show" + toolbar] = true;
                });
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.selectAll = function () {
                for (var i = 0; i < $scope.dataList.length; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                getBillIds();
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.selectSingle = function (item) {
                var selectAll = false;
                if (!item.isChecked) {
                    selectAll = false;
                } else {
                    selectAll = checkAll($scope.dataList);
                }
                $scope.markInfo.allChecked = selectAll;
                getBillIds();
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.tdDetailClick = function (item, fnType) {
                switch (fnType) {
                    case "viewPurchaseNoDetail":
                        viewPurchaseNoDetail(item);
                        break;
                    default:
                        break;
                }
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function viewDetail(item) {
                invoiceNo = item.invoiceNo;
                getDetailDataList(1);
                $scope.changeTab(1);
            }
            function viewPurchaseNoDetail(item) {
                EventBus.Publish('go2otherMenuPage', { name: "app.sales.purchaseApply",
                    'params':{"purchaseNo"
                          :item.purchaseNo,
                         }
                       });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            function getDataList(curPage) {
                $scope.markInfo.curRow = -1;

                var service = "device",
                    reqUrl = "/invoice/list",
                    param = {
                        pageSize: $scope.pageInfo.pageSize,
                        pageNum: $scope.pageInfo.curPage,
                        filters: angular.copy($scope.condition)
                    };

                if (!!curPage) {
                    param.pageNum = $scope.pageInfo.curPage = curPage;
                }

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.orderDateF = $filter("YbDate")(item.orderDate, df);
                        item.postDateF = $filter("YbDate")(item.postDate, df);
                        item.createDateF = $filter("YbDate")(item.createDate, df);
                        item.signDateF = $filter("YbDate")(item.signDate, df);
                        item.signState = $filter("ProgressStatus")(item.isSign, 'signState');
                        item.invoiceTypeShow = $filter("InvoiceType")(item.invoiceType);
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function initData() {
                $scope.markInfo.allChecked = false;
                invoiceNo = "";
                $scope.detailPage.condition = {};
                $scope.detailPage.dataList = [];
            }

            /*********************** 详情页开始 ***********************/
            $scope.detailPage = {};
            $scope.detailPage.markInfo = {
                curRow: -1
            };
            $scope.detailPage.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.detailPage.condition = {};
            $scope.detailPage.dataList = [];
            $scope.detailPage.toolbarConfig = {};
            $scope.detailPage.tableConfig = {
                scrollWidth: 1960,
                tableCol: [
                    {
                        name: "开票凭证",
                        dataField: "invoiceNo",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "纸质发票号",
                        dataField: "invoicePaperNo",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "采购订单号",
                        dataField: "purchaseNo",
                        width: 145,
                        toSort: false,
                        isShow: $scope.isWJ,
                        type: "click",
                        clickFn: "viewPurchaseNoDetail"
                    },
                    {
                        name: "发货通知单单号",
                        dataField: "deliveryNo",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "发货通知单项目号",
                        dataField: "deliveryProNo",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "销售和分销凭证号",
                        dataField: "saleDistNo",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "销售和分销凭证的项目号",
                        dataField: "saleDistProNo",
                        width: 170,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "会计凭证编号",
                        dataField: "accountNo",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "会计凭证中的行项目数",
                        dataField: "accountRowNo",
                        width: 160,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "零件号",
                        dataField: "materialsNo",
                        width: 130,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "外部零件组",
                        dataField: "outMaterialsGroup",
                        width: 130,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "成交总价",
                        dataField: "unitPrice",
                        width: 120,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "当前票据金额",
                        dataField: "totalPrice",
                        width: 120,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "单据创建日期",
                        dataField: "orderDateF",
                        width: 130,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "过账日期",
                        dataField: "postDateF",
                        width: 130,
                        isShow: true,
                        toSort: false
                    }
                ]
            };

            $scope.detailPage.search = function (curpage) {
                getDetailDataList(curpage);
            };

            $scope.detailPage.reset = function () {
                $scope.detailPage.condition = {};
            };

            $scope.detailPage.switchToolbar = function (toolbar) {
                if (!!$scope.detailPage.toolbarConfig["show" + toolbar]) {
                    $scope.detailPage.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.detailPage.toolbarConfig["show" + toolbar] = true;
                });
            };

            $scope.detailPage.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.detailPage.selectRow = function (index) {
                $scope.detailPage.markInfo.curRow = index
            };


            function getDetailDataList(curPage) {
                $scope.detailPage.markInfo.curRow = -1;

                var service = "device",
                    reqUrl = "/invoice/detailList",
                    param = {
                        pageSize: $scope.detailPage.pageInfo.pageSize,
                        pageNum: $scope.detailPage.pageInfo.curPage,
                        filters: angular.copy($scope.detailPage.condition)
                    };

                if (!!curPage) {
                    param.pageNum = $scope.detailPage.pageInfo.curPage = curPage;
                }

                param.filters.invoiceNo = invoiceNo;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {
                        item.orderDateF = $filter("YbDate")(item.orderDate, df);
                        item.postDateF = $filter("YbDate")(item.postDate, df);
                    });
                    $scope.detailPage.pageInfo.totalRows = resp.value.total;
                    $scope.detailPage.pageInfo.totalPages = resp.value.pages;
                    $scope.detailPage.dataList = resp.value.list;
                });
            }

            /*********************** 详情页结束 ***********************/

            $scope.sign = function (id) {
                var service = "device";
                var reqUrl = "/invoice/sign";
                ybWidget.ShowConfirm("确定要签收吗？", "签收说明").then(function (note) {
                    var param = {
                        id: id,
                        signNote: note
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                });
            };

            $scope.edit = function (item) {
                $scope.invoiceObj = item;
                $scope.changeTab(2)
            };

            $scope.saveData = function () {
                saveData($scope.invoiceObj).then(function () {
                    getDataList();
                    $scope.changeTab(0);
                })
            };

            function saveData(param) {
                var service = "device";
                var reqUrl = "/invoice/update";
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    return resp;
                });
            }

            $scope.updateSAP = function () {
                var service = "device";
                var reqUrl = "/invoice/sapPost";
                ybHttp.Post(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                });
            };

            $scope.syncContractNumber = function () {
                var service = "device";
                var reqUrl = "/invoice/updateWjInvoicePaperNo";
                ybHttp.Post(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                });
            };

            $scope.syncSAPHistory = function () {
                $scope.changeTab(3);
            };
            $scope.syncSAPHistoryHandle = function () {
                var service = "device";
                var params = {
                    startDateStr: formatSyncDate($scope.syncTime.startDateStr),
                    endDateStr: formatSyncDate($scope.syncTime.endDateStr)
                }
                var reqUrl = `/invoice/sapPostTimeIntervalData?startDateStr=${params.startDateStr}&endDateStr=${params.endDateStr}`;
              
                ybHttp.Post(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                });
            };

            function formatSyncDate(date) {
                var date = new Date(date);
                var year = date.getFullYear();
                var month = ('0' + (date.getMonth() + 1)).slice(-2);
                var day = ('0' + date.getDate()).slice(-2);
                var formattedDate = year + month + day;
                return formattedDate;
            }

            (function () {
                if ($scope.isZHJCH) {
                    var newTableConfig = angular.copy($scope.tableConfig);
                    $scope.tableConfig.scrollWidth = 1540;
                    $scope.tableConfig.tableCol = [];
                    angular.forEach(newTableConfig.tableCol, function (item) {
                        if (item.type !== 'operate') {
                            $scope.tableConfig.tableCol.push(angular.copy(item));
                        }
                    });
                }

                getDataList(1);
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);